package org.zhadoop.stream.cql.semanticanalyzer;

import java.util.List;

import org.zhadoop.stream.api.streams.Schema;
import org.zhadoop.stream.cql.exception.SemanticAnalyzerException;
import org.zhadoop.stream.cql.semanticanalyzer.analyzecontext.AnalyzeContext;
import org.zhadoop.stream.cql.semanticanalyzer.analyzecontext.InsertAnalyzeContext;
import org.zhadoop.stream.cql.semanticanalyzer.analyzecontext.SelectAnalyzeContext;
import org.zhadoop.stream.cql.semanticanalyzer.parser.context.InsertStatementContext;
import org.zhadoop.stream.cql.semanticanalyzer.parser.context.ParseContext;

/**
 * insert 语义分析
 * @author zwd
 *
 */
public class InsertStatementAnalyzer extends BaseAnalyzer {

	private InsertAnalyzeContext context = null;
	
	private InsertStatementContext insertContext;
	
	public InsertStatementAnalyzer(ParseContext parseContext) throws SemanticAnalyzerException {
		super(parseContext);
		insertContext = (InsertStatementContext) parseContext;
	}

	@Override
	public AnalyzeContext analyze() throws SemanticAnalyzerException {
		String streamName = insertContext.getStreamName();
		context.setOutputStreamName(streamName);
		
		if(checkSchemaExists(streamName)){
			context.setOutputSchema(getSchemaByName(streamName));
		}else{
			context.setPipeStreamNotCreated(true);
		}
		 analyzeSelectStatement();
	     createOutputStream();
		return context;
	}

	private void createOutputStream() {
		
	}

	private void analyzeSelectStatement() throws SemanticAnalyzerException{
		SemanticAnalyzer selectAnalyzer = SemanticAnalyzerFactory.createAnalyzer(insertContext.getSelect(),getAllSchemas());
		
		if(selectAnalyzer instanceof SelectStatementAnalyzer){
			((SelectStatementAnalyzer) selectAnalyzer).setOutputStreamName(context.getOutputStreamName());
		}
		
		context.setSelectContext((SelectAnalyzeContext)selectAnalyzer.analyze());
	}

	@Override
	protected AnalyzeContext getAnalyzeContext() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void createAnalyzeContext() {
		// TODO Auto-generated method stub
		
	}

	public InsertAnalyzeContext getContext() {
		return context;
	}

	public void setContext(InsertAnalyzeContext context) {
		this.context = context;
	}

	public InsertStatementContext getInsertContext() {
		return insertContext;
	}

	public void setInsertContext(InsertStatementContext insertContext) {
		this.insertContext = insertContext;
	}
	
}
